package main

import (
	"fmt"
	"lcss/assets"
	"lcss/util"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/glebarez/sqlite"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var db *gorm.DB
var config *Config

func Init() {
	// 初始化Viper
	viper.SetConfigFile("config.ini")
	viper.ReadInConfig()
}

func initDB(config *Config) *gorm.DB {
	var db *gorm.DB
	var err error
	dbMode := config.DBMode

	fmt.Println(dbMode) // Preserving user's original logging
	if dbMode == "mysql" {
		dsn := config.DBUser + ":" + config.DBPassword + "@tcp(" + config.DBHost + ":" + config.DBPort + ")/" + config.DBDatabase + "?charset=" + config.DBCharset + "&parseTime=True&loc=Local"
		fmt.Println(dsn) // Preserving user's original logging
		db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	} else if dbMode == "sqlite" {
		db, err = gorm.Open(sqlite.Open(config.SQLitePath), &gorm.Config{})
	} else {
		panic(fmt.Sprintf("Invalid or missing db_mode in config: '%s'. Must be 'mysql' or 'sqlite'. Please check your config.ini.", dbMode))
	}

	if err != nil {
		panic(fmt.Sprintf("Failed to connect to database (mode: %s): %v", dbMode, err))
	}

	db.AutoMigrate(&TSysUser{}, &TSysFile{}, &TGoviewProject{}, &TGoviewProjectData{})
	user := &TSysUser{}
	err = db.Model(&user).First(&user).Error
	// 没有用户，自动创建管理用户
	if err != nil || user.Password == "" {
		duser := CreateDefaultUser()
		db.Create(&duser)
	}

	return db
}

func main() {

	// 初始化Viper
	Init()
	config = ReadConfig()
	// 读取配置
	db = initDB(config)
	// 设置Gin模式
	gin.SetMode(config.Mode)

	router := gin.Default()

	router.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	// 设置静态文件路由
	// 参数 "static" 表示 URL 的前缀，"./static" 表示静态文件所在的目录
	router.Static("/static", "./static")
	// 参数 "assets" 表示 URL 的前缀，"./assets" 表示q嵌入静态文件所在的目录
	router.StaticFS("/assets", http.FS(assets.FS))

	// Public routes (without authentication)
	router.GET("/", Index)

	goview := router.Group("/api/goview/sys")
	goview.POST("/login", Login)
	goview.GET("/logout", Logout)
	goview.GET("/getOssInfo", GetOssInfo)
	goview.POST("/register", Register)
	router.GET("/api/goview/project/getData", ProjectDataGet)
	goViewProject := router.Group("/api/goview/project")
	goViewProject.Use(AuthMiddleware())
	goViewProject.POST("/create", ProjectCreate)
	goViewProject.POST("/edit", ProjectEdit)
	goViewProject.DELETE("/delete", ProjectDelete)
	goViewProject.GET("/list", PorjectListGet)
	goViewProject.PUT("/publish", ProjectPublish)
	goViewProject.POST("/upload", ProjectUpload)
	// goViewProject.GET("/getData", ProjectDataGet)
	goViewProject.POST("/save/data", ProjectDataSave)

	// Authenticated routes (with JWT authentication)
	// auth := router.Group("/auth")
	// auth.Use(AuthMiddleware())
	{
		// auth.POST("/users", CreateNewUser)
		// Add other authenticated routes here
	}

	util.OpenBrowser(fmt.Sprintf("http://localhost:%s", config.Port))

	router.Run(":" + config.Port)
}
